package com.mindskip.xzs.controller.admin;

import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.base.SystemCode;
import com.mindskip.xzs.domain.Question;
import com.mindskip.xzs.domain.TextContent;
import com.mindskip.xzs.domain.enums.QuestionTypeEnum;
import com.mindskip.xzs.domain.question.QuestionItemObject;
import com.mindskip.xzs.domain.question.QuestionObject;
import com.mindskip.xzs.repository.QuestionMapper;
import com.mindskip.xzs.repository.QuestionRepository;
import com.mindskip.xzs.repository.TextContentRepository;
import com.mindskip.xzs.service.FileUpload;
import com.mindskip.xzs.service.QuestionService;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.utility.*;
import com.mindskip.xzs.viewmodel.admin.question.QuestionEditRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionPageRequestVM;
import com.mindskip.xzs.viewmodel.admin.question.QuestionResponseVM;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController("AdminQuestionController")
@RequestMapping(value = "/api/admin/question")
public class QuestionController extends BaseApiController {

    private final QuestionService questionService;
    private final TextContentService textContentService;

    @Autowired
    public QuestionController(QuestionService questionService, TextContentService textContentService) {
        this.questionService = questionService;
        this.textContentService = textContentService;
    }

//    Logger.getLogger(;)

    private final Logger logger = LoggerFactory.getLogger(QuestionController.class);

    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<QuestionResponseVM>> pageList(@RequestBody QuestionPageRequestVM model) {
        PageInfo<Question> pageInfo = questionService.page(model);
        PageInfo<QuestionResponseVM> page = PageInfoHelper.copyMap(pageInfo, q -> {
            QuestionResponseVM vm = modelMapper.map(q, QuestionResponseVM.class);
            vm.setCreateTime(DateTimeUtil.dateFormat(q.getCreateTime()));
            vm.setScore(ExamUtil.scoreToVM(q.getScore()));
            TextContent textContent = textContentService.selectById(q.getInfoTextContentId());
//            logger
            logger.info("textContent {}", textContent);
            if (textContent == null) {
//                return RestResponse.fail(RestResponse.haveNotDone,"空的 ");
//                return RestResponse.error(page);
                return null;
            }
            QuestionObject questionObject = JsonUtil.toJsonObject(textContent.getContent(),
                    QuestionObject.class);
            logger.info("questionObject {}", questionObject);
//            String titleContent = questionObject.getTitleContent();
//            if(titleContent==null){
//                vm.setShortTitle(null);
//            }
            String clearHtml = HtmlUtil.clear(questionObject.getTitleContent());
            logger.info("clearHtml {}", clearHtml);
            vm.setShortTitle(clearHtml);
            logger.info("vm {}", vm);
            return vm;
        });
        return RestResponse.ok(page);
    }

    @Resource
    QuestionMapper questionMapper;

    @Resource
    TextContentRepository textContentRepository;
    @Resource
    QuestionRepository questionRepository;


    @PostMapping(value = "/findAllTextContents")
    public RestResponse findAllTextContents(@RequestBody List<Question> questions) {
        List<TextContent> textContents = textContentRepository.findAll();
        for (TextContent textContent : textContents) {
            String content = textContent.getContent();
            System.out.println(content);
        }
        return RestResponse.ok(textContents);
    }

//    TextContentService textContentService;
//
//    TextContentRepository textContentRepository;

    public void setQuestionInfoFromVM(TextContent infoTextContent, Question model) {
//        List<QuestionItemObject> itemObjects = model.getItems().stream().map(i ->
//                {
//                    QuestionItemObject item = new QuestionItemObject();
//                    item.setPrefix(i.getPrefix());
//                    item.setContent(i.getContent());
//                    item.setItemUuid(i.getItemUuid());
//                    item.setScore(ExamUtil.scoreFromVM(i.getScore()));
//                    return item;
//                }
//        ).collect(Collectors.toList());
        List<QuestionItemObject> itemObjects = model.getItems();
        QuestionObject questionObject = new QuestionObject();
        questionObject.setQuestionItemObjects(itemObjects);
        questionObject.setAnalyze(model.getAnalyze());
        questionObject.setTitleContent(model.getTitle());
        questionObject.setCorrect(model.getCorrect());
        infoTextContent.setContent(JsonUtil.toJsonStr(questionObject));
    }

    @PostMapping(value = "/insertBatch")
    public RestResponse insertBatch(@RequestBody List<Question> questions) {
//        for (Question question : questions) {
//            question.ge
//        }

//        textContentService.jsonConvertUpdate()

//        List<TextContent> textContents = questions.stream().
//                map(o -> {
////                    String quesContent = o.getQuesContent();
//                    String quesContent = o.getItems();
//                    TextContent textContent = new TextContent();
//                    textContent.setContent(quesContent);
//                    textContent.setCreateTime(new Date());
//                    return textContent;
//                }).collect(Collectors.toList());
//        questionService.se

        List<TextContent> textContents = questions.stream().map(o -> {
//            List<QuestionItemObject> items = o.getItems();
            TextContent infoTextContent = new TextContent();
            setQuestionInfoFromVM(infoTextContent, o);
            return infoTextContent;
        }).collect(Collectors.toList());

        List<TextContent> textContents1 = textContentRepository.saveAll(textContents);
        Question question = new Question();

//        Object allFiledName = ObjectToJson.getAllFiledName(question);
        String jsonAllFiled = ObjectToJson.Object2JsonAllFiled(question);

//        questions.stream().map(o->{
//            o.setInfoTextContentId();
//        })
        int idx = 0;
        for (Question question1 : questions) {
            TextContent textContent = textContents1.get(idx);
            idx++;
            question1.setInfoTextContentId(textContent.getId());
            question1.setDeleted(false);
            question1.setStatus(Question.Status.normal);
        }
        /**
         * [{"name":"单选题","questionItems":[{"id":21,"itemOrder":1},{"id":18,"itemOrder":2}]},{"name":"多选题","questionItems":[{"id":22,"itemOrder":3},{"id":33,"itemOrder":4}]},{"name":"判断题","questionItems":[{"id":43,"itemOrder":5},{"id":30,"itemOrder":6}]},{"name":"填空题","questionItems":[{"id":27,"itemOrder":7},{"id":39,"itemOrder":8},{"id":28,"itemOrder":9}]},{"name":"简答题","questionItems":[{"id":48,"itemOrder":10},{"id":41,"itemOrder":11},{"id":40,"itemOrder":12}]}]
         */

        List<Question> questions1 = questionRepository.saveAll(questions);
//        questionMapper.insertBatch(questions);
        ReturnT returnT = new ReturnT();
        returnT.setExampleCode(jsonAllFiled);
        returnT.setData(questions1);
        return RestResponse.ok(returnT);
    }

//    @PostMapping(value = "/insertBatch")
//    public RestResponse insertBatch(@RequestBody List<Question> questions) {
////        for (Question question : questions) {
////            question.ge
////        }
//
////        textContentService.jsonConvertUpdate()
//
//        List<TextContent> textContents = questions.stream().
//                map(o -> {
////                    String quesContent = o.getQuesContent();
//                    String quesContent = o.getItems();
//                    TextContent textContent = new TextContent();
//                    textContent.setContent(quesContent);
//                    textContent.setCreateTime(new Date());
//                    return textContent;
//                }).collect(Collectors.toList());
//        List<TextContent> textContents1 = textContentRepository.saveAll(textContents);
//        Question question = new Question();
//
////        Object allFiledName = ObjectToJson.getAllFiledName(question);
//        String jsonAllFiled = ObjectToJson.Object2JsonAllFiled(question);
//
////        questions.stream().map(o->{
////            o.setInfoTextContentId();
////        })
//        int idx = 0;
//        for (Question question1 : questions) {
//            TextContent textContent = textContents1.get(idx);
//            idx++;
//            question1.setInfoTextContentId(textContent.getId());
//            question1.setDeleted(false);
//            question1.setStatus(Question.Status.normal);
//        }
//        /**
//         * [{"name":"单选题","questionItems":[{"id":21,"itemOrder":1},{"id":18,"itemOrder":2}]},{"name":"多选题","questionItems":[{"id":22,"itemOrder":3},{"id":33,"itemOrder":4}]},{"name":"判断题","questionItems":[{"id":43,"itemOrder":5},{"id":30,"itemOrder":6}]},{"name":"填空题","questionItems":[{"id":27,"itemOrder":7},{"id":39,"itemOrder":8},{"id":28,"itemOrder":9}]},{"name":"简答题","questionItems":[{"id":48,"itemOrder":10},{"id":41,"itemOrder":11},{"id":40,"itemOrder":12}]}]
//         */
//
//        List<Question> questions1 = questionRepository.saveAll(questions);
////        questionMapper.insertBatch(questions);
//        ReturnT returnT = new ReturnT();
//        returnT.setExampleCode(jsonAllFiled);
//        returnT.setData(questions1);
//        return RestResponse.ok(returnT);
//    }


    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public RestResponse edit(@RequestBody @Valid QuestionEditRequestVM model) {
        RestResponse validQuestionEditRequestResult = validQuestionEditRequestVM(model);
        if (validQuestionEditRequestResult.getCode() != SystemCode.OK.getCode()) {
            return validQuestionEditRequestResult;
        }

//        questionService.in
//        questionMapper.

        if (null == model.getId()) {
//            新的
            questionService.insertFullQuestion(model, getCurrentUser().getId());
        } else {
            questionService.updateFullQuestion(model);
        }

        return RestResponse.ok();
    }

    @RequestMapping(value = "/select/{id}", method = RequestMethod.POST)
    public RestResponse<QuestionEditRequestVM> select(@PathVariable Integer id) {
        QuestionEditRequestVM newVM = questionService.getQuestionEditRequestVM(id);
        return RestResponse.ok(newVM);
    }


    @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
    public RestResponse delete(@PathVariable Integer id) {
        Question question = questionService.selectById(id);
        question.setDeleted(true);
        questionService.updateByIdFilter(question);
        return RestResponse.ok();
    }

    private RestResponse validQuestionEditRequestVM(QuestionEditRequestVM model) {
        int qType = model.getQuestionType().intValue();
        boolean requireCorrect = qType == QuestionTypeEnum.SingleChoice.getCode() || qType == QuestionTypeEnum.TrueFalse.getCode();
        if (requireCorrect) {
            if (StringUtils.isBlank(model.getCorrect())) {
                String errorMsg = ErrorUtil.parameterErrorFormat("correct", "不能为空");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }

//        填空题
        if (qType == QuestionTypeEnum.GapFilling.getCode()) {
            Integer fillSumScore = model.getItems().stream().mapToInt(d -> ExamUtil.scoreFromVM(d.getScore())).sum();
            Integer questionScore = ExamUtil.scoreFromVM(model.getScore());
            if (!fillSumScore.equals(questionScore)) {
                String errorMsg = ErrorUtil.parameterErrorFormat("score", "空分数和与题目总分不相等");
                return new RestResponse<>(SystemCode.ParameterValidError.getCode(), errorMsg);
            }
        }
        return RestResponse.ok();
    }
}
